<template>
  <transition name="showHeader">
    <div v-if="visible" class="header-animat">
      <a-layout-header v-if="visible" :key="'header'" :style="{ padding: '0' }">
        <div :class="['top-nav-header-index', theme]">
          <div class="header-index-wide" style="max-width: unset">
            <div class="header-index-left" style="flex: auto">
              <logo class="top-nav-header" :show-title="device !== 'mobile'" />
            </div>
            <user-menu class="header-index-right" :theme="theme"></user-menu>
          </div>
        </div>
      </a-layout-header>
    </div>
  </transition>
</template>

<script lang="ts">
import UserMenu from '../tools/UserMenu/index.vue'
import Logo from '../tools/Logo.vue'
import { defineComponent, ref, onMounted, onBeforeUnmount } from 'vue'
import {
  sidebarOpened,
  device,
  fixedHeader,
  autoHideHeader
} from '@/store/useSiteSettings'

export default defineComponent({
  name: 'GlobalHeader',
  components: {
    UserMenu,
    Logo
  },
  props: {
    theme: {
      type: String,
      required: false,
      default: 'dark'
    }
  },
  setup(props, { emit }) {
    const visible = ref<boolean>(true)
    const oldScrollTop = ref<number>(0)
    const ticking = ref<boolean>(false)
    // 下滑时隐藏 Header
    const handleScroll = () => {
      if (!autoHideHeader.value) {
        return
      }

      const scrollTop = document.body.scrollTop + document.documentElement.scrollTop
      if (!ticking.value) {
        ticking.value = true
        requestAnimationFrame(() => {
          if (oldScrollTop.value > scrollTop) {
            visible.value = true
          } else if (scrollTop > 200 && visible.value) {
            visible.value = false
          } else if (scrollTop < 200 && !visible.value) {
            visible.value = true
          }
          oldScrollTop.value = scrollTop
          ticking.value = false
        })
      }
    }

    const toggle = () => {
      emit('toggle')
    }

    onMounted(() => {
      document.addEventListener('scroll', handleScroll, { passive: true })
    })

    onBeforeUnmount(() => {
      document.body.removeEventListener('scroll', handleScroll, true)
    })

    const refreshPage = () => {
      emit('refresh')
    }

    return {
      visible,
      fixedHeader,
      sidebarOpened,
      toggle,
      device,
      refreshPage
    }
  }
})
</script>

<style lang="less">
@import '../../style/index.less';

.header-animat {
  position: relative;
  z-index: @ant-global-header-zindex;
}
.showHeader-enter-active {
  transition: all 0.25s ease;
}
.showHeader-leave-active {
  transition: all 0.5s ease;
}
.showHeader-enter,
.showHeader-leave-to {
  opacity: 0;
}
</style>
